﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using FileMonitor.Configuration.Tool.Controls.Prototype;

namespace FileMonitor.Configuration.Tool.Controls
{
    public enum Mode
    {
        Edit = 0,
        Add = 1
    }
    public partial class DatabaseEditor : UserControl
    {
        private string sqlStringFomat = "Database={0};Server={1};User Id={2};Password={3};";
        private Mode _mode = Mode.Edit;
        public DatabaseEditor()
        {
            InitializeComponent();
            this.textPassword.Leave += new EventHandler(textPassword_Leave);
        }

        void textPassword_Leave(object sender, EventArgs e)
        {
            List<string> dbs = GetDBNameList();
            this.comboBox1.DataSource = dbs;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string connstr = GetConnString(true);
            this.lblConnString.Text = connstr;
        }

        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            if (ValidateConnection())
            {
                MessageBox.Show("Connetction Successful!!");
            }
            else
            {
                MessageBox.Show("Connetction Failure!!");
            }
        }

        private List<string> GetDBNameList()
        {
            string connStr = GetConnString(false);
            try
            {
                List<string> dbs = new List<string>();
                string sql = "select name from sys.databases where database_id > 4";
                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    conn.Open();
                    IDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        dbs.Add(dr["name"].ToString());
                    }
                    dr.Close();
                }
                return dbs;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Can't not find Database ,please confirm database permission");
            }
            return null;
        }

        //public string ConnString 
        //{
        //    get
        //    {
        //        return "";
        //    }
        //}

        public delegate void SaveDBHandler(object sender, DBEditorArgs args);
        public delegate void DeleteDBHandler(object sender, DBEditorArgs args);


        public event SaveDBHandler Save;
        public event SaveDBHandler Delete;

        private void OnDelete(string connstring)
        {
            if (Delete != null)
            {
                string dbName = this.txtDBName.Text;
                DBEditorArgs args = new DBEditorArgs(dbName, connstring, this._mode);
                Delete(this, args);
            }
        }


        private void OnSave(string connstring)
        {
            if (Save != null)
            {
                string dbName = this.txtDBName.Text;
                if (string.IsNullOrEmpty(dbName))
                {
                    MessageBox.Show("Database Name Can't be null");
                }
                if (ValidateConnection())
                {
                    DBEditorArgs args = new DBEditorArgs(dbName, connstring, this._mode);
                    Save(this, args);
                }
                else
                {
                    MessageBox.Show("The Connection is invalidation,can' save it");
                }

            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string connStr = GetConnString(true);
            OnSave(connStr);
        }

        private string GetConnString(bool withDB)
        {
            string serverName = this.txtServerName.Text.Trim();
            string username = this.textUserName.Text.Trim();
            string password = this.textPassword.Text.Trim();
            string dbName = "";
            if (withDB)
            {
                dbName = this.comboBox1.SelectedValue.ToString();
            }
            string connStr = string.Format(sqlStringFomat, dbName, serverName, username, password);

            return connStr;
        }


        private bool ValidateConnection()
        {
            string connStr = GetConnString(true);
            bool flag = false;
            try
            {
                using (SqlConnection conn = new SqlConnection(connStr))
                {

                    conn.Open();
                    conn.Close();
                    flag = true;
                }
            }
            catch (Exception ex)
            {
                flag = false;
            }
            return flag;
        }


        public Mode Mode
        {
            get { return this._mode; }
            set
            {
                if (value == Mode.Edit)
                {
                    this.txtDBName.ReadOnly = true;
                    this.btnDelete.Visible = true;
                }
                this._mode = value;
            }
        }


        public void BindConnString(string connString, string connName)
        {
            string serverName = Utility.GetValueFormConnstring(connString, "Server");
            string username = Utility.GetValueFormConnstring(connString, "User Id");
            string password = Utility.GetValueFormConnstring(connString, "Password");
            string dbName = Utility.GetValueFormConnstring(connString, "Database");
            this.txtServerName.Text = serverName;
            this.textUserName.Text = username;
            this.textPassword.Text = password;
            this.txtDBName.Text = connName;
            this.lblConnString.Text = connString;
            List<string> dbs = GetDBNameList();
            this.comboBox1.DataSource = dbs;
            this.comboBox1.Text = dbName;

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            OnDelete(this.lblConnString.Text);
        }
    }
}
